package com.example.flashApp.usage

import android.app.Service
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.SystemClock
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Calendar

class UsageTrackingService : Service() {

    private lateinit var repository: UsageRepository
    private val scope = CoroutineScope(Dispatchers.IO)
    private val trackingInterval = 15 * 60 * 1000L // 15 minutes

    override fun onCreate() {
        super.onCreate()
        repository = UsageRepository(applicationContext)
        startTracking()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    private fun startTracking() {
        scope.launch {
            while (true) {
                trackUsage()
                SystemClock.sleep(trackingInterval)
            }
        }
    }

    private fun trackUsage() {
        val usageStatsManager = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        val calendar = Calendar.getInstance()
        val endTime = calendar.timeInMillis
        calendar.add(Calendar.DAY_OF_MONTH, -1)
        val startTime = calendar.timeInMillis

        val usageStats = usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY,
            startTime,
            endTime
        )

        usageStats.forEach { usageStat ->
            val usageEntity = UsageEntity(
                packageName = usageStat.packageName,
                totalTimeInForeground = usageStat.totalTimeInForeground,
                timestamp = endTime
            )
            repository.insertUsageStats(usageEntity)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // Clean up resources if needed
    }
}
